package com.sxm.yiwei.activitis;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.adapters.HotSendLinkItemAdapter;
import com.sxm.yiwei.tools.BookPayActivity;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class HotSendBookActivity extends BaseActivity implements View.OnClickListener{
    private String TAG = "hotsend";
    private TextView bookprice;
    private TextView bookdistance;
    private Button case1,case2,case3;
    private TextView hotbook;
    private List<HashMap<String, String>> contData;
    private List<HashMap<String, String>> link;
    private Button sendbook;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;
    private List<String> imglist;
    private String explain;
    private String weight;
    private String time;
    private String v;
    private String alldistance;
    private String tip;
    private String urgent;
    private String safe;
    private String password;
    private DecimalFormat df;
    private double money;
    private TextView sendaddress;
    private ListView hotlistview;
    private AlertDialog dialog;
    private ImageView sendbookback;
    private TextView casetext;
    private ImageView backmain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hot_send_book);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid","1");
        userId = sharedPreferences.getString("userId", "0");
        token = sharedPreferences.getString("token", "2");
        initHotSendBookView();
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        v = extras.getString("v");
        safe = extras.getString("safe");
        df = new DecimalFormat("######0.0");
        alldistance = extras.getString("alldistance");
        time = extras.getString("time");
        weight = extras.getString("weight");
        explain = extras.getString("explain");

        contData = (List<HashMap<String, String>>) extras.getSerializable("cont");
        link = (List<HashMap<String, String>>) extras.getSerializable("link");

        imglist = (List<String>) extras.getSerializable("imglist");
        // 显示价格
        bookprice.setText(v);
        bookdistance.setText(alldistance);
        sendaddress.setText(link.get(0).get("name")+" "+link.get(0).get("address"));
        List<HashMap<String,String>> linkdata = new ArrayList<>();
        for (int i = 1; i < link.size(); i++) {

            linkdata.add(link.get(i));

        }
        HotSendLinkItemAdapter adapter = new HotSendLinkItemAdapter(this,linkdata);
        hotlistview.setAdapter(adapter);
        hotlistview.setEnabled(false);
        tip="0";
        urgent="0";

    }

    private void initHotSendBookView() {
        casetext = (TextView) findViewById(R.id.hot_casetext);
        bookprice = (TextView) findViewById(R.id.hotsend_bookprice);
        bookdistance = (TextView) findViewById(R.id.hotsend_bookdistance);
        sendbookback = (ImageView) findViewById(R.id.hotsendbook_back);
        // 小费按钮
        case1 = (Button) findViewById(R.id.hotsend_caseprice1);//5yuan
        case2 = (Button) findViewById(R.id.hotsend_caseprice2);// 10
        case3 = (Button) findViewById(R.id.hotsend_caseprice3);// 20
        hotbook = (TextView) findViewById(R.id.hotsend_hotbook); // 加急
        sendaddress = (TextView) findViewById(R.id.hotsend_address);
        hotlistview = (ListView) findViewById(R.id.hotbook_listview);
        sendbook = (Button) findViewById(R.id.hotsend_sendbook);
        backmain = (ImageView) findViewById(R.id.hotsendbook_backmain);
        backmain.setOnClickListener(this);
        case1.setOnClickListener(this);
        case2.setOnClickListener(this);
        case3.setOnClickListener(this);
        hotbook.setOnClickListener(this);
        sendbook.setOnClickListener(this);
        sendbookback.setOnClickListener(this);
    }
    Double casemoney = 0.0;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.hotsendbook_backmain:
                startActivity(new Intent(HotSendBookActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
            case R.id.hotsendbook_back:
                finish();
                break;
            case R.id.hotsend_caseprice1:
                if (case1.isSelected()){
                    case1.setSelected(false);
                    casemoney=0.0;
                    tip="0";
                }else {
                    case1.setSelected(true);
                    casemoney=5.0;
                    tip="5";
                }
                case2.setSelected(false);
                case3.setSelected(false);
                casetext.setText("小费 "+casemoney+" 元");
                break;
            case R.id.hotsend_caseprice2:
                if (case2.isSelected()){
                    case2.setSelected(false);
                    casemoney=0.0;
                    tip="0";
                }else {
                    case2.setSelected(true);
                    casemoney=10.0;
                    tip="10";
                }
                case1.setSelected(false);
                case3.setSelected(false);
                casetext.setText("小费 "+casemoney+" 元");
                break;
            case R.id.hotsend_caseprice3:
                if (case3.isSelected()){
                    case3.setSelected(false);
                    casemoney=0.0;
                    tip="0";
                }else {
                    case3.setSelected(true);
                    casemoney=20.0;
                    tip="20";
                }
                casetext.setText("小费 "+casemoney+" 元");
                case1.setSelected(false);
                case2.setSelected(false);

                break;
            case  R.id.hotsend_hotbook:

                boolean selected = hotbook.isSelected();
                if (selected==false){
                    hotbook.setSelected(true);
                    String text = (String) bookprice.getText();
                    double v1 = Double.valueOf(text) * 1.5;
                    df = new DecimalFormat("######0.0");
                    bookprice.setText(String.valueOf(df.format(v1)));
                    urgent="1";
                }else {
                    hotbook.setSelected(false);
                    String text = (String) bookprice.getText();
                    double v1 = Double.valueOf(text) / 1.5;
                    df = new DecimalFormat("######0.0");
                    bookprice.setText(String.valueOf(df.format(v1)));
                    urgent="0";
                }
                break;
            case R.id.hotsend_sendbook:
                AlertDialog.Builder builder = new AlertDialog.Builder(HotSendBookActivity.this,R.style.NoBackGroundDialog);
                View view = LayoutInflater.from(this).inflate(R.layout.progress_dialog, null);

                builder.setView(view);
                dialog = builder.create();
                dialog.show();

               sendBookContent();

                break;

        }

    }


        //发布订单
    private void sendBookContent() {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.SENDHOTBOOK);
        params.addHeader("Content-Type","multipart/form-data");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        params.addBodyParameter("consignorId",link.get(0).get("id"));
        params.addBodyParameter("insurance",safe);// 保价
        params.addBodyParameter("appointTime",time);
        params.addBodyParameter("weight",weight);
        params.addBodyParameter("tip",tip);// 小费
        params.addBodyParameter("urgent",urgent);// 加急
        params.addBodyParameter("distance", alldistance);// 距离
        params.addBodyParameter("total_amount",String.valueOf(Double.valueOf(String.valueOf(bookprice.getText()))+casemoney));// 总价
        Log.d(TAG, "sendBookContent: 你好--订单发布--"+tip+"//"+urgent+"//"+(Double.valueOf(String.valueOf(bookprice.getText()))+casemoney));
        JSONArray array = new JSONArray();
        for (int i = 0; i < contData.size(); i++) {
            JSONObject ob = new JSONObject();
            ob.put("consigneeId",contData.get(i).get("consigneeId"));
            ob.put("distance",contData.get(i).get("distance"));
            array.add(ob);
        }
       params.addBodyParameter("consignees",  array.toJSONString());
        params.addBodyParameter("intro",explain);
        for (int i = 0; i < imglist.size(); i++) {
            params.addBodyParameter("order",new File(imglist.get(i)));// 图片
        }
        params.setMultipart(true);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d(TAG, "onSuccess: 发单--"+result);

                JSONObject object = JSON.parseObject(result);
                String data = object.getString("data");
                String status = object.getString("status");
                if (status.equals("1")){
                    JSONObject object1 = JSON.parseObject(data);
                    String orderId = object1.getString("orderId");

                    Double dMoney = Double.valueOf(String.valueOf(bookprice.getText()));
                    money = casemoney + dMoney;

                    Intent in = new Intent(HotSendBookActivity.this,BookPayActivity.class);
                    in.putExtra("from","hot");
                    in.putExtra("amount",String.valueOf(money));
                    in.putExtra("id",orderId);
                    in.putExtra("alipay",InternetAddressUtis.SENDBOOK_ALIPAY);
                    in.putExtra("yivipay",InternetAddressUtis.ONE_SENDPAY);
                    startActivity(in);
                    finish();
                }else {
                    if (status.equals("0")){
                        String failure = object.getString("failure");
                        if (failure.equals("1061")){
                            Toast.makeText(HotSendBookActivity.this, "价格计算错误", Toast.LENGTH_SHORT).show();
                        }
                    }

                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d(TAG, "onError: 发单--"+ex);
              //  ErrType.errType(HotSendBookActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                dialog.dismiss();
            }
        });
    }

}
